import Utils from './CommonUtil';
import DateUtils from './DateUtils';

export default class CacheUtils {

  /**
   * 保存缓存数据
   * @param key
   * @param value
   * @param duration
   * @constructor
   */
  static Set(key, value, duration) {

    if (Utils.empty(key) || Utils.empty(value)) return;

    let data = {
      value: value,
      expiryTime: !duration || isNaN(duration) ? 0 : DateUtils.time() + parseInt(duration)
    };
    localStorage[key] = JSON.stringify(data);
  }

  /**
   *
   * 获取缓存数据
   * @param key
   * @returns {null}
   * @constructor
   */
  static Get(key) {
    let data = localStorage[key];
    if (Utils.empty(data)) return null;

    let now = DateUtils.time();
    let obj;
    try {
      obj = JSON.parse(data);
    } catch (e) {
      return null;
    }
    if (obj.expiryTime === 0 || obj.expiryTime > now) return obj.value;
    return null;
  }

  /**
   * 清除缓存
   * @param key
   * @constructor
   */
  static Clear(key) {
    if (Utils.empty(key)) return;
    localStorage.removeItem(key);
  }


  /**
   * 获取用户登录缓存数据
   * @param key
   * @returns {*}
   * @constructor
   */
  static GetUserInfo(key){

    let info = CacheUtils.Get('userInfo');
    if (Utils.empty(key)) return info;

    if (Utils.empty(info)) return null;

    let value = '';
    eval('value = info.' + key);
    return value;
  }

  static ClearUserInfo(){
    CacheUtils.Clear('userInfo');
  }


}
